//
//  DownloadViewController.m
//  On The Load
//
//  Created by 我爱的妞 on 15/11/17.
//  Copyright © 2015年 @@叶一闽. All rights reserved.
//

#import "DownloadViewController.h"

@interface DownloadViewController () <NSURLSessionDataDelegate, NSURLSessionDelegate, NSURLSessionDownloadDelegate,NSURLSessionTaskDelegate>

@property (nonatomic, strong) NSURLSession *urlSession;

@property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask;

@property (nonatomic, strong) NSData *partialData;

@end

@implementation DownloadViewController

+ (instancetype)shareDownloadHandle{
    
    static DownloadViewController *shareD = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        shareD = [[DownloadViewController alloc] init];
    });
    
    return shareD;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
}

- (void)startDownload{
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_downUrl]];
    
    //NSURLSessionConfiguration 用于配置会话的属性(默认会话,即时会话,后台回话)
    self.urlSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
    self.downloadTask = [self.urlSession downloadTaskWithRequest:request];
    
    [self.downloadTask resume];
    
}

#pragma mark NSURL协议

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    
    NSData *data = [NSData dataWithContentsOfURL:location];
    
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *createPath = [NSString stringWithFormat:@"%@/Image", pathDocuments];
    
    NSString *path = [NSString stringWithFormat:@"%@.mp4", _titleStr];
    NSString *docPath = [createPath stringByAppendingPathComponent:path];
    NSLog(@"%@", docPath);
    // 判断文件夹是否存在，如果不存在，则创建
    if (![[NSFileManager defaultManager] fileExistsAtPath:createPath]) {
        [fileManager createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    [data writeToFile:docPath atomically:YES];
    NSFileManager *manager = [NSFileManager defaultManager];
    [manager removeItemAtURL:location error:nil];
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    
    double current = totalBytesWritten / (double)totalBytesExpectedToWrite;
    
    dispatch_queue_t conCurrentQueue = dispatch_queue_create("com.lanou3g.GCD.ConCurrent", DISPATCH_QUEUE_CONCURRENT);
    //执行队列
    dispatch_async(conCurrentQueue, ^{
        _currentProgress = current;
    });
    
}

@end
